<template>
  <PageWrapper v-loading="loadingRef" contentFullHeight fixedHeight dense>
    <AdVxeTable
      @register="registerTable"
      @fetch-success="clearSelectedRows"
      @fetch-error="clearSelectedRows"
      @checkbox-change="
        () => {
          hasRowSelected = getSelectedRows()?.length > 0;
        }
      "
    >
      <template #tools>
        <Authority :value="'Root.Admin.Msg.Message.Create'">
          <a-button type="primary" @click="handleCreate">
            <Icon icon="ant-design:plus-circle-outlined" />{{ t('common.addText') }}
          </a-button>
        </Authority>
        <Authority :value="'Root.Admin.Msg.Message.Delete'">
          <a-button
            type="primary"
            color="error"
            :disabled="!hasRowSelected"
            @click="handleDeleteBatch"
          >
            <Icon icon="ant-design:delete-outlined" />{{ t('common.delText') }}
          </a-button>
        </Authority>
      </template>

      <template #iconCol="{ row }">
        <TableImg
          :size="30"
          :simpleShow="true"
          :showBadge="false"
          :imgList="[row?.Icon]"
          :fallback="infoImage"
        />
      </template>
      <template #actionCol="{ row }">
        <TableAction
          outside
          :actions="[
            {
              icon: 'ant-design:delete-outlined',
              color: 'error',
              tooltip: t('common.delText'),
              auth: 'Root.Admin.Msg.Message.Delete', // 权限控制
              // ifShow: (_action) => {
              //   return !record.SendTime; // 根据业务控制是否显示: 是否可删除的数据权限状态
              // },
              popConfirm: {
                title: t('common.delConfirmText'),
                placement: 'left',
                confirm: handleDelete.bind(null, row),
              },
            },
          ]"
          :dropDownActions="[
            {
              icon: 'clarity:details-line',
              label: t('common.detailText'),
              onClick: handleDetail.bind(null, row),
            },
            {
              icon: 'clarity:note-edit-line',
              label: t('common.editText'),
              auth: 'Root.Admin.Msg.Message.Update', // 权限控制
              ifShow: (_action) => {
                return !row?.IsSent; // 根据业务控制是否显示: 是否可删除的数据权限状态
              },
              onClick: handleEdit.bind(null, row),
            },
            {
              icon: 'icon-park-outline:send-email',
              label: t('routes.system.message.sendMessageText'),
              auth: 'Root.Admin.Msg.Message.Send', // 权限控制
              ifShow: (_action) => {
                return !row?.IsSent || !row?.BaseType; // 根据业务控制是否显示: 是否可删除的数据权限状态
              },
              onClick: handleSend.bind(null, row),
            },
          ]"
        />
      </template>
    </AdVxeTable>

    <MessageDetailModal
      @register="registerDetailModal"
      @sendmsg="reloadTable"
      :afterSubmitFunc="handleAfterDetailSubmit"
    />
  </PageWrapper>
</template>
<script lang="ts" setup>
  import { ref, h } from 'vue';
  import { useI18n } from '@/hooks/web/useI18n';
  import { isString } from '@/utils/is';
  import { Authority } from '@/components/Authority';
  import { PageWrapper } from '@/components/Page';
  import { AdVxeTable, useAdVxeTable, TableAction, TableImg } from '@/components/AdVxeTable';
  import { useMessage } from '@/hooks/web/useMessage';

  import Icon from '@/components/Icon/Icon.vue';
  import infoImage from '@/assets/images/info_2x.png';

  import { MessageOutputDto } from '@/api/message/admin/message/model';
  import { readMessages, deleteMessages, sendMessages } from '@/api/message/admin/message';
  import { AjaxResult } from '#/request';
  import { useModal } from '@/components/AdVxeModal';
  import { FormModeEnum } from '@/enums/formEnum';

  import { columns } from './message.data';

  import MessageDetailModal from './detail.vue';

  defineOptions({ name: 'MessagePage' });

  const { t } = useI18n();
  const { createConfirm, createMessage, createErrorModal } = useMessage();
  const hasRowSelected = ref(false);

  const loadingRef = ref(false);

  const [registerTable, { getTable, reload: reloadTable }] = useAdVxeTable({
    id: 'system-message-page-table',
    // 表标题呈现器
    title: t('routes.system.message.message.listText'),
    // 表格数据接口请求对象
    api: readMessages,
    // 表单列信息 AdColumn[]
    columns: columns,
    // 使用搜索表单
    searchForm: true,
    //行选择设置
    selection: 'checkbox',
    // 是否带有边框 boolean | default（默认）, full（完整边框）, outer（外边框）, inner（内边框）, none（无边框）
    border: false,
    // 是否显示序号列
    showSeqColumn: true,
    // 表格右侧操作列配置 AdColumn
    actionColumn: {
      width: 80,
      title: t('common.actionText'),
      fixed: 'right',
      slots: { default: 'actionCol' },
    },
  });

  function getSelectedRows() {
    const $table = getTable();
    if ($table) {
      const rows = $table.getCheckboxRecords();
      return rows;
    }
    return [];
  }
  function clearSelectedRows() {
    const $table = getTable();
    if ($table) {
      $table.clearCheckboxRow();
    }
  }

  const [registerDetailModal, detailModalMethods] = useModal();
  /** 处理查看详情 */
  async function handleDetail(record: any) {
    detailModalMethods.openModal(true, {
      formMode: FormModeEnum.ReadOnly,
      record: record,
    });
  }
  /** 处理创建 */
  async function handleCreate() {
    detailModalMethods.openModal(true, {
      formMode: FormModeEnum.Add,
      record: null,
    });
  }
  /** 处理编辑 */
  async function handleEdit(record: any) {
    detailModalMethods.openModal(true, {
      formMode: FormModeEnum.Edit,
      record: record,
    });
  }
  /** 处理发送 */
  async function handleSend(record: any) {
    if (record && record.Id) {
      try {
        loadingRef.value = true;
        var reulst = await sendMessages([record.Id]);
        if (reulst.Succeeded) {
          createMessage.success(t('common.successText'));
          await reloadTable();
        }
      } finally {
        loadingRef.value = false;
      }
    }
  }
  /** 处理删除 */
  async function handleDelete(record: any) {
    // console.log(record);
    if (record && record.Id) {
      try {
        loadingRef.value = true;
        const result = await deleteMessages([record.Id]);
        if (result.Succeeded) {
          createMessage.success(t('common.successText'));
          await reloadTable();
          clearSelectedRows();
        }
      } finally {
        loadingRef.value = false;
      }
    }
  }
  /** 处理批量删除 */
  async function handleDeleteBatch() {
    const selectedRows = getSelectedRows();
    if (selectedRows?.length > 0) {
      createConfirm({
        zIndex: 999999999,
        iconType: 'warning',
        title: () => h('span', t('sys.app.logoutTip')),
        content: () => h('span', t('common.delConfirmText')),
        onOk: async () => {
          try {
            loadingRef.value = true;
            const recordIds = selectedRows.map((item) => {
              return item.Id;
            });
            const result = await deleteMessages(recordIds);
            if (result.Succeeded) {
              createMessage.success(t('common.successText'));
              await reloadTable();
              clearSelectedRows();
            }
          } finally {
            loadingRef.value = false;
          }
        },
      });
    }
  }

  /** 处理详情表单提交后回调，返回true关闭窗体 */
  /** 处理详情表单提交后回调，返回true关闭窗体 */
  async function handleAfterDetailSubmit(
    formMode: FormModeEnum,
    result?: AjaxResult | null,
    _record?: MessageOutputDto | null,
  ) {
    if (result) {
      if (result?.Succeeded) {
        if (result?.Content) {
          createMessage.success(result.Content);
        } else {
          createMessage.success(t('common.successText'));
        }
        switch (formMode) {
          case FormModeEnum.Add:
          case FormModeEnum.Edit:
          case FormModeEnum.Delete:
            await reloadTable();
            break;
        }
        return true;
      } else {
        if (result?.Data && isString(result?.Data)) {
          createErrorModal({
            zIndex: 999999999,
            title: () => h('span', t('sys.api.errorTip')),
            content: () => h('span', result?.Data),
          });
        }
        return false;
      }
    }
    return true;
  }
</script>
